package net.towee.client.com.app.view;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.HasOpenHandlers;
import com.google.gwt.event.logical.shared.OpenEvent;
import com.google.gwt.event.logical.shared.OpenHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;

import net.towee.client.com.app.presenter.ConnectionControllerPresenter.Display;
import net.towee.client.i18n.ToweeConstants;
import net.towee.client.i18n.ToweeMessages;
import net.towee.client.resources.ClientResource;
import net.towee.client.widgets.SpanPanel;
import net.towee.server.sio.common.ConnectionState;
import net.towee.server.sio.common.DisconnectReason;

public class ConnectionControllerView extends FlowPanel implements Display {
	private final ClientResource resource;
	private final ToweeConstants constants;
	private final ToweeMessages messages;

	@Inject
	public ConnectionControllerView(ToweeConstants constants, ClientResource resource, ToweeMessages messages) {
		this.constants = constants;
		this.resource = resource;
		this.messages = messages;
	}
	
	@Override
	public void showDisconnectedMessage() {
		// Show and clear parent
		getParent().setVisible(true);
		clear();
		add( new SpanPanel(constants.connectionLost()+" ") );
	}
	
	public void showConnectingMessage() {
		getParent().setVisible(true);
		clear();
		add(new SpanPanel(constants.connecting()));
	}

	@Override
	public void showConnectedMessage() {
		getParent().setVisible(false);
	}

	@Override
	public void showReconnectingMessage(final int dur, final int att) {
		getParent().setVisible(true);
		clear();
		
		final SpanPanel timerPanel = new SpanPanel();
		add( new SpanPanel(messages.reconnecting(att)+" ") );
		add(timerPanel);
		
		// Reconnection timer
		final Timer timer = new Timer() {
			private int count = dur/1000-1;
			
			@Override
			public void run() {
				timerPanel.setText(count+"");
				
				if(count-- == 0) {
					cancel();
				}
			}
		};
		timer.scheduleRepeating(1000);
	}

	@Override
	public void showFailureMessage() {
		getParent().setVisible(true);
		clear();
		add(new SpanPanel(constants.connectionFailure() ));		
	}

}
